Android 连接 MySQL 并进行基本的增删改查操作 您所在的位置:网站首页 安卓 mysql管理 Android 连接 MySQL 并进行基本的增删改查操作

Android 连接 MySQL 并进行基本的增删改查操作

2024-06-08 11:23| 来源: 网络整理| 查看: 265

准备工作导入 jar 包 下载 mysql-connector-java 包(吃过亏的表示推荐 5.x.x 版本,8.x.x 版本会出现挺多问题的):mysql-connector-java 下载地址 打开 AS,将 jar 包复制到 libs 文件夹下, 复制完后右键 jar 包,点击 “add as library”,将 jar 包导入相应 module 如果导入的 mysql-connector-java 版本为 8.x.x,则需要在 app\build.gradle 中添加:12345678android { // ... compileOptions { sourceCompatibility 1.8 targetCompatibility 1.8 }} 添加网络权限

在 AndroidManifest.xml 中添加:1

在本地主机的 mysql 中创建要连接的数据库

使用命令行创建数据库

1create database ;

使用 navicat 等可视化工具直接创建数据库

连接 MySql

直接上工具类:1234567891011121314151617181920212223242526272829303132333435363738394041424344454647/** * @author Feng Zhaohao * Created on 2019/11/24 */public class DbOpenHelper { private static String driver = "com.mysql.jdbc.Driver";// mysql 驱动 private static String ip = "xxx.xxx.xxx.xxx"; // 安装了 mysql 的电脑的 ip 地址 private static String dbName = "TestDB"; // 要连接的数据库 private static String url = "jdbc:mysql://" + ip + ":3306/" + dbName + "?useUnicode=true&characterEncoding=utf8"; // mysql 数据库连接 url private static String user = "root"; // 用户名 private static String password = "xxxxxx"; // 密码 private static Connection sConnection; /** * 连接数据库 */ public static Connection getConnection() { if (sConnection == null) { try { Class.forName(driver); // 获取 mysql 驱动 sConnection = DriverManager.getConnection(url, user, password); // 获取连接 } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } return sConnection; } /** * 关闭数据库 */ public static void closeConnection() { if (sConnection != null) { try { sConnection.close(); } catch (SQLException e) { e.printStackTrace(); } } }}

通过 getConnection() 获得连接,不需要连接时记得使用 closeConnection() 关闭。

注意:

url 连接中的 ip 地址是指本地主机(安装了 mysql 的电脑)的 ip 地址,不是 localhost(localhost 是你手机的 ip 地址,你手机不可能装 mysql 吧) url 连接中的数据库名不要写错,必须是本地主机的 mysql 中已经创建好的数据库 需要在子线程中进行连接 MySQL 操作 连接后进行增删改查

准备工作:在 TestDB 数据库中创建了一个 person 表,该表有 3 个 column: id(int 类型,主键,自增长)、name(text 类型,表示姓名)、age(int 类型,表示年龄)。

注意:连接 MySQL 和对 MySQL 数据库进行增删改查操作都需要放在子线程中进行,不然会抛出异常。

插入数据123456789101112131415161718192021222324252627282930/** * 插入数据(插入一条姓名为 name,年龄为 age 的数据) */public static void insert(String name, int age) { // 插入数据的 sql 语句 String sql = "insert into person (name, age) values (?, ?)"; Connection connection = DbOpenHelper.getConnection(); PreparedStatement ps = null; if (connection == null) { return; } try { ps = connection.prepareStatement(sql); // 为两个 ? 设置具体的值 ps.setString(1, name); ps.setInt(2, age); // 执行语句 ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } }} 更新数据123456789101112131415161718192021222324252627/** * 更新数据(将姓名为 name 的年龄改为 newAge) */public static void update(String name, int newAge) { // 更新数据的 sql 语句 String sql = "update person set age = ? where name = ?"; Connection connection = DbOpenHelper.getConnection(); PreparedStatement ps = null; try { ps = connection.prepareStatement(sql); // 为两个 ? 设置具体的值 ps.setInt(1, newAge); ps.setString(2, name); // 执行语句 ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } }} 删除数据1234567891011121314151617181920212223242526/** * 删除数据(删除姓名为 name 的数据) */public static void delete(String name) { // 删除数据的 sql 语句 String sql = "delete from person where name = ?"; Connection connection = DbOpenHelper.getConnection(); PreparedStatement ps = null; try { ps = connection.prepareStatement(sql); // 为 ? 设置具体的值 ps.setString(1, name); // 执行语句 ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } }} 查询数据123456789101112131415161718192021222324252627282930313233343536373839404142434445/** * 查询 person 表的所有数据 */public static String query() { // 查询的 sql 语句 String sql = "select * from person"; Connection connection = DbOpenHelper.getConnection(); PreparedStatement ps = null; ResultSet rs = null; StringBuilder builder = new StringBuilder(); try { ps = connection.prepareStatement(sql); // 执行语句(执行查询语句用的是 executeQuery 方法) rs = ps.executeQuery(); // 得到查询结果 if (rs != null) { while (rs.next()) { builder.append("[name = "); builder.append(rs.getString("name")); builder.append(", age = "); builder.append(rs.getInt("age")); builder.append("] "); } } } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return builder.toString();} 出现的问题

下面是对在连接 MySQL 过程中出现问题的记录,其中问题 2、问题 4、问题 5 是导入 mysql-connector-java-8.x.x 出现的问题;问题 6 是导入 mysql-connector-java-5.x.x 出现的问题。

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

1解决:在项目中导入 mysql-connector-java 包

Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver.

1解决:将 mysql 驱动由 "com.mysql.jdbc.Driver" 换成 "com.mysql.cj.jdbc.Driver"

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

123原因:连接的数据库(在连接 url 中指定的数据库)未创建(很多博客都没有说这点,结果一开始我傻傻地以为随便输入一个数据库名就行)解决:连接前先在本地创建好需要连接的数据库

java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

1解决:在连接 url 中添加 serverTimezone,例如 "jdbc:mysql://ip:3306/dbName?serverTimezone=GMT%2B8"

java.lang.ClassNotFoundException: Didn’t find class “java.sql.SQLType” on path: DexPathList…

12345原因:推测和 jdk1.8 版本有关,但是在 IDEA 上用 Java 连接 MySql 又正常,有点迷解决:放弃 mysql-connector-java-8.x.x,重新导了个更低版本的 mysql-connector-java-5.x.x(又回到最初的起点...)。注意,导了 5.x.x 版本后问题 2、问题 4 就不存在了。

Unknown initial character set index ‘255’ received from server. Initial client character

1解决: 在连接 url 指定字符集,例如 "jdbc:mysql://ip:3306/dbName?useUnicode=true&characterEncoding=utf8" 参考 Android 连接MySQL数据库并进行增删改查操作 mysql-connector-java与Mysql、Java的对应版本 Unknown initial character set index ‘255’ received from server. Initial client character 解决方法 springboot 连接MySQL的时候报错The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrec Host is not allowed to connect to this MySQL server解决方法


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有